package com.ukao.steward.ui.valetRunners.waitingOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.WaitingOrderAdapter;
import com.ukao.steward.base.IAdapter;
import com.ukao.steward.base.IPage;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.base.PageWrapper;
import com.ukao.steward.bean.WaitingOrderBean;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.OrderReceivDialogFragment;
import com.ukao.steward.eventbus.MainEvent;
import com.ukao.steward.eventbus.WorkEvent;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.listener.OnItemChildClickListener;
import com.ukao.steward.pesenter.valetRunners.WaitingOrderPesenter;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.view.valetRunners.WaitingOrderView;
import com.ukao.steward.widget.MyLRecyclerView;
import com.ukao.steward.widget.StateButton;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 待接单
 */
public class WaitingOrderFragment extends MvpFragment<WaitingOrderPesenter> implements WaitingOrderView {


    @BindView(R.id.lrecycler_view)
    MyLRecyclerView lrecyclerView;
    Unbinder unbinder;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.not_woke_txt)
    TextView notWokeTxt;
    @BindView(R.id.start_work_btn)
    StateButton startWorkBtn;
    @BindView(R.id.woke_layout)
    RelativeLayout wokeLayout;
    @BindView(R.id.wait_order_layout)
    FrameLayout waitOrderLayout;
    private String mParam1;
    private String mParam2;
    private ArrayList<WaitingOrderBean.ListBean> mData;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private WaitingOrderAdapter mWaitingOrderAdapter;
    private PageWrapper mPageWrapper;
    private View view;
    private View mEmptyView;


    public static WaitingOrderFragment newInstance(String param1, String param2) {
        WaitingOrderFragment fragment = new WaitingOrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected WaitingOrderPesenter createPresenter() {
        return new WaitingOrderPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_waiting_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setStatusBarTintColor(R.color.colorPrimary);
            if (SaveParams.getIsRest()){
                lrecyclerView.forceToRefresh();
            }

    }

    @Override
    protected void initView() {
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        mData = new ArrayList<>();
        mEmptyView = view.findViewById(R.id.empty_view);
        // lrecyclerView.setEmptyView(mEmptyView);//设置在setAdapter之前才能生效
        initLinearRecyclerView(lrecyclerView);
        title.setText("待接单");
        mWaitingOrderAdapter = new WaitingOrderAdapter(_mActivity, mData);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mWaitingOrderAdapter);
        lrecyclerView.setAdapter(mLRecyclerViewAdapter);
        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {
                mvpPresenter.waitOrder(geIndex, pageSize);


            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);
        setWaitingType();

    }


    @Override
    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(WorkEvent event) {

        switch (event.getMessage()) {
            case WOKE_STATE:
                setWaitingType();
                if (SaveParams.getIsRest()) {
                    lrecyclerView.forceToRefresh();
                }
                break;


        }
    }

  public   void setWaitingType() {
        if (SaveParams.getIsRest()) {
            wokeLayout.setVisibility(View.GONE);
            waitOrderLayout.setVisibility(View.VISIBLE);


        } else {
            wokeLayout.setVisibility(View.VISIBLE);
            waitOrderLayout.setVisibility(View.GONE);

        }
    }

    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {
            mEmptyView.setVisibility(CheckUtils.isEmpty(data) ? View.VISIBLE : View.GONE);
            mWaitingOrderAdapter.getDataList().clear();
            mWaitingOrderAdapter.setDataList(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            lrecyclerView.setLoadMoreEnabled(isNextLoad);

        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {
            mWaitingOrderAdapter.addAll(data);
            mLRecyclerViewAdapter.notifyDataSetChanged();
            if (!isNextLoad) lrecyclerView.setNoMore(!isNextLoad);

        }
    };


    @Override
    protected void initListener() {
        super.initListener();
        lrecyclerView.setOnRefreshListener(mOnRefreshListener);
        lrecyclerView.setOnLoadMoreListener(mOnLoadMoreListener);
        mWaitingOrderAdapter.setOnItemChildClickListener(mOnItemChildClick);
        mLRecyclerViewAdapter.setOnItemClickListener(mOnItemClickListener);
    }


    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            WaitingOrderBean.ListBean mitem = mWaitingOrderAdapter.getCount(position);
            OrderdetailFragment  mOrderdetailFragment=OrderdetailFragment.createBuilder()
                    .orderId(mitem.getId())
                    .build();
            start(mOrderdetailFragment);
        }
    };

    private OnItemChildClickListener mOnItemChildClick = new OnItemChildClickListener() {
        @Override
        public void onChildItemClick(int id, int pos, Object item) {
            L.i("pos=" + pos);
            WaitingOrderBean.ListBean items = mWaitingOrderAdapter.getCount(pos);
            switch (id) {
                case R.id.robOrdid_btn:/*接单*/
                    mvpPresenter.receiving(items);

                    break;
                case R.id.refuse_btn:/*拒絕*/
                    mvpPresenter.reject(items);
                    break;
            }
        }
    };


    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {

            mLRecyclerViewAdapter.notifyDataSetChanged();
            mPageWrapper.loadPage(true);
        }
    };
    private OnLoadMoreListener mOnLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            mPageWrapper.loadPage(false);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.back_btn,R.id.start_work_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case  R.id.start_work_btn:
                mvpPresenter.setSatrtWorking();

                break;

        }
    }


    @Override
    public void waitOrderSucceed(WaitingOrderBean mWaitingOrderBean) {
        mPageWrapper.addDataSource(mWaitingOrderBean.getList(), mWaitingOrderBean.getPages());
    }

    @Override
    public void loadfinish() {
        lrecyclerView.refreshFinish();
    }


    @Override
    public void receivingSucceed(WaitingOrderBean.ListBean mListBean, String msg) {

        mWaitingOrderAdapter.getDataList().remove(mListBean);
        mLRecyclerViewAdapter.notifyDataSetChanged();
        OrderReceivDialogFragment.createBuilder(getChildFragmentManager())
                .isReceivingSucceed(true)
                .orderId(mListBean.getId())
                .mDialogSubmitListener(mDialogSubmitListener)
                .show();

    }

    @Override
    public void receivingFail(String orderId, String msg) {
        OrderReceivDialogFragment.createBuilder(getChildFragmentManager())
                .isReceivingSucceed(false)
                .orderId(orderId)
                .errorMsg(msg)
                .mDialogSubmitListener(mDialogSubmitListener)
                .show();
    }


    /**
     * 开始工作
     */
    @Override
    public void satrtWorkingSucceed() {
        lrecyclerView.forceToRefresh();
        setWaitingType();
        MainEvent.postNoData(MainEvent.Message.START_WORK);


    }

    private DialogSubmitListener mDialogSubmitListener = (DialogSubmitListener)
            (parent, message) ->

                    start(OrderdetailFragment.createBuilder()
                            .orderId((String) message)
                            .isValuation(true)
                            .build());
}
